package com.boyuan.aboutcase;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.boyuan.huijiaoyu.ColorHolderApplication;
import com.boyuan.huijiaoyu.R;
import com.easemob.EMCallBack;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.example.contactfragment.ContactGroupService;
import com.example.contactfragment.GroupMember;
import com.example.contactfragment.HomeContactMyGroupActivity;
import com.example.contactfragment.MyGroup;
import com.example.huanxin.ChatActivity;
import com.example.huanxin.Constant;
import com.example.huanxin.more.HXSDKHelper;
import com.example.huanxin.more.User2;
import com.example.huanxin.more.UserDao;
import com.example.newfragment.CaseListEntity;
import com.example.newfragment.HomeService;
import com.magicsoft.app.entity.CaseDetailEntity;
import com.magicsoft.app.entity.GroupForCaseIdEntity;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.weitown.fragment.HomeList;
import com.ttcaca.cas.android.client.utils.Helper;

public class CaseViewPagerActivity extends Activity {

	private Context context = null;
	private LocalActivityManager manager;
	private boolean progressShow;
	private ContactGroupService contactgroupService;
	ArrayList<GroupForCaseIdEntity> groups = new ArrayList<GroupForCaseIdEntity>();
	ArrayList<View> Activitylist = new ArrayList<View>();
	private ViewPager mPager;
	String TAG = "CaseViewPagerActivity";

	@SuppressWarnings("deprecation")
	private boolean isGetInFoFinish = false;
	private String caseid;
	private String groupname;
	private HomeService homeService;
	private CaseDetailEntity caseDetailEntity;
	String groupid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_case_view_pager);
		isGetInFoFinish = false;
		context = CaseViewPagerActivity.this;
		manager = new LocalActivityManager(this, true);
		manager.dispatchCreate(savedInstanceState); 
		Intent intent = getIntent();
		caseid = intent.getStringExtra("caseid");
//		getCaseDetailInfo();
		SharedPreferences sp = getSharedPreferences("cgid", 0);
		groupid = sp.getString(caseid, "");
		if(groupid == null || ("".equals(groupid))){
			getCaseDetailInfo2();
		}
		groupname = intent.getStringExtra("groupname");
		LoginChat();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				if (isGetInFoFinish) {
					initPager();
					return;
				} else {
					new Handler().postDelayed(this, 1000);
				}
			}
		}, 1000);
//		initPager();

	}


	private void initPager() {
		mPager = (ViewPager) findViewById(R.id.pager);
		Intent intent = new Intent(this, CaseDetailActivity.class);
		Activitylist.add(getView("CaseDetailActivity", intent));
		if(groupid == null || ("".equals(groupid))){
			Helper.showToast(CaseViewPagerActivity.this, "未获取到gid");
		}else{
			Intent intent2 = new Intent(CaseViewPagerActivity.this,
					ChatActivity.class);
			View view2 = getView("ChatActivity", intent2);
			if (view2 != null) {
				Activitylist.add(view2);
			}
		}
		MyPagerAdapter myPagerAdapter = new MyPagerAdapter(Activitylist);
		mPager.setAdapter(myPagerAdapter);
	}

	@SuppressWarnings("deprecation")
	private View getView(String id, Intent intent) {

		if ("CaseDetailActivity".equals(id)) {
			if (caseid != null) {
				intent.putExtra("caseid", caseid);
			}
			if (manager != null) {
				return manager.startActivity(id, intent).getDecorView();
			}
		} else if ("ChatActivity".equals(id)) {
			if (groupid != null && !"".equals(groupid)) {
				intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
				intent.putExtra("groupId", groupid);
				intent.putExtra("groupName", groupname);
				intent.putExtra("caseid", caseid);
				intent.putExtra("back", "群组");
				return manager.startActivity(id, intent).getDecorView();
			} else {
				Helper.showToast(CaseViewPagerActivity.this, "没有获取到群组ID");
				return null;
			}
		}
		return null;
	}

	@SuppressWarnings("deprecation")
	private void LoginChat() {
		progressShow = true;
		final ProgressDialog pd = new ProgressDialog(this);
		pd.setCanceledOnTouchOutside(false);
		pd.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				progressShow = false;
			}
		});
		pd.setMessage(getString(R.string.Is_landing2));
		pd.show();

		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		String username = sp.getString("username", "18030095903");
		String mima = "" + username.substring(5, username.length());

		EMChatManager.getInstance().login(username, mima, new EMCallBack() {

			@Override
			public void onSuccess() {
				if (!progressShow) {
					return;
				}
				try {
					// ** manually load all local groups and
					EMGroupManager.getInstance().loadAllGroups();
					EMChatManager.getInstance().loadAllConversations();
					initializeContacts();
					asyncFetchContactsFromServer();
				} catch (Exception e) {
					e.printStackTrace();
					runOnUiThread(new Runnable() {
						public void run() {
							pd.dismiss();
							ColorHolderApplication.getInstance().logout(null);
							Toast.makeText(getApplicationContext(),
									R.string.login_failure_failed, 1).show();
						}
					});
					return;
				}
				boolean updatenick = EMChatManager.getInstance()
						.updateCurrentUserNick(
								ColorHolderApplication.currentUserNick.trim());

				if (!updatenick) {
				}
				if (!isFinishing() && pd.isShowing()) {
					pd.dismiss();
				}
				isGetInFoFinish = true;
			}

			private void asyncFetchContactsFromServer() {

				HXSDKHelper.getInstance().asyncFetchContactsFromServer(
						new EMValueCallBack<List<String>>() {

							@Override
							public void onSuccess(List<String> usernames) {
								Context context = HXSDKHelper.getInstance()
										.getAppContext();

								Map<String, User2> userlist = new HashMap<String, User2>();
								for (String username : usernames) {
									User2 user = new User2();
									user.setUsername(username);
									setUserHearder(username, user);
									userlist.put(username, user);
								}
								User2 newFriends = new User2();
								newFriends
										.setUsername(Constant.NEW_FRIENDS_USERNAME);
								String strChat = context
										.getString(R.string.Application_and_notify);
								newFriends.setNick(strChat);

								userlist.put(Constant.NEW_FRIENDS_USERNAME,
										newFriends);
								User2 groupUser = new User2();
								String strGroup = context
										.getString(R.string.group_chat);
								groupUser.setUsername(Constant.GROUP_USERNAME);
								groupUser.setNick(strGroup);
								groupUser.setHeader("");
								userlist.put(Constant.GROUP_USERNAME, groupUser);

								User2 chatRoomItem = new User2();
								String strChatRoom = context
										.getString(R.string.chat_room);
								chatRoomItem.setUsername(Constant.CHAT_ROOM);
								chatRoomItem.setNick(strChatRoom);
								chatRoomItem.setHeader("");
								userlist.put(Constant.CHAT_ROOM, chatRoomItem);

								ColorHolderApplication.getInstance()
										.setContactList(userlist);
								UserDao dao = new UserDao(context);
								List<User2> users = new ArrayList<User2>(
										userlist.values());
								dao.saveContactList(users);

								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(true);

								if (HXSDKHelper.getInstance()
										.isGroupsSyncedWithServer()) {
									HXSDKHelper.getInstance()
											.notifyForRecevingEvents();
								}

							}

							@Override
							public void onError(int error, String errorMsg) {
								HXSDKHelper.getInstance()
										.notifyContactsSyncListener(false);
							}

						});

			}

			private void setUserHearder(String username, User2 user) {
				String headerName = null;
				if (!TextUtils.isEmpty(user.getNick())) {
					headerName = user.getNick();
				} else {
					headerName = user.getUsername();
				}
				if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
					user.setHeader("");
				} else if (Character.isDigit(headerName.charAt(0))) {
					user.setHeader("#");
				} else {
					user.setHeader(HanziToPinyin.getInstance()
							.get(headerName.substring(0, 1)).get(0).target
							.substring(0, 1).toUpperCase());
					char header = user.getHeader().toLowerCase().charAt(0);
					if (header < 'a' || header > 'z') {
						user.setHeader("#");
					}
				}
			}

			private void initializeContacts() {
				Map<String, User2> userlist = new HashMap<String, User2>();
				User2 newFriends = new User2();
				newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
				String strChat = getResources().getString(
						R.string.Application_and_notify);
				newFriends.setNick(strChat);
				userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
				User2 groupUser = new User2();
				String strGroup = getResources().getString(R.string.group_chat);
				groupUser.setUsername(Constant.GROUP_USERNAME);
				groupUser.setNick(strGroup);
				groupUser.setHeader("");
				userlist.put(Constant.GROUP_USERNAME, groupUser);
				ColorHolderApplication.getInstance().setContactList(userlist);
				UserDao dao = new UserDao(CaseViewPagerActivity.this);
				List<User2> users = new ArrayList<User2>(userlist.values());
				dao.saveContactList(users);

			}

			@Override
			public void onProgress(int progress, String status) {
			}

			@Override
			public void onError(final int code, final String message) {
				if (!progressShow) {
					return;
				}
				runOnUiThread(new Runnable() {
					public void run() {
						pd.dismiss();
						Toast.makeText(getApplicationContext(),
								getString(R.string.Login_failed) + message,
								Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
	}

	public class MyPagerAdapter extends PagerAdapter {
		List<View> list = new ArrayList<View>();

		public MyPagerAdapter(ArrayList<View> list) {
			this.list = list;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ViewPager pViewPager = ((ViewPager) container);
			pViewPager.removeView(list.get(position));
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			ViewPager pViewPager = ((ViewPager) arg0);
			pViewPager.addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}
	
	
//	private void getCaseDetailInfo() {
//		if (homeService == null) {
//			homeService = new HomeService(this);
//		}
////		SharedPreferences sp = getSharedPreferences("a.xml", 0);
////		String corp_id = sp.getString("username", "");
//		homeService.GetCaseDetail(caseid, "1",
//				new GetMultilParamsListener() {
//
//					@Override
//					public void onFinish(Object... params) {
//						caseDetailEntity = (CaseDetailEntity) params[0];
//					}
//
//					@Override
//					public void onFailed(String Message) {
//						ToastHelper.showMsg(CaseViewPagerActivity.this, Message, false);
//					}
//				});
//	}
	
	private void getCaseDetailInfo2() {
	if (homeService == null) {
		homeService = new HomeService(this);
	}
	homeService.getCaseAndIm(caseid,
			new GetMultilParamsListener() {

				@Override
				public void onFinish(Object... params) {
					caseDetailEntity = (CaseDetailEntity) params[0];
					groupid = caseDetailEntity.getGid();
				}

				@Override
				public void onFailed(String Message) {
					ToastHelper.showMsg(CaseViewPagerActivity.this, Message, false);
				}
			});
}
	
}
